package br.com.salao.model;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import org.apache.log4j.Logger;

import br.com.salao.entity.Servicos;
import br.com.salao.session.ServicosBase;
import br.com.salao.util.Utils;

public class ServicosModel {

	private Logger logger = Logger.getLogger(ServicosModel.class.getName());

	public boolean incluir(Servicos servicos, String horaMinuto) throws ParseException{

		Date time;
		DateFormat formata = new SimpleDateFormat("HH:mm");
		time = (Date)formata.parse(horaMinuto);
		logger.info(time.toString());

		servicos.setDuracaoServico(time);

		try{
			ServicosBase servicosBase = getBean();
			servicosBase.inserir(servicos);
			return true;
		}catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getCause() + "\n");
			sb.append(e.getMessage() + "\n");
			sb.append(e.getStackTrace());

			logger.error(sb.toString());

			e.printStackTrace();

			return false;
		}
	}


	public List<Servicos> listar(){	
		try{
			ServicosBase servicosBase = getBean();
			return servicosBase.listar();
		}catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getCause() + "\n");
			sb.append(e.getMessage() + "\n");
			sb.append(e.getStackTrace());
			
			logger.error(sb.toString());
			
			e.printStackTrace();

			return null;
		}
	}

	public Servicos buscarServicoPorId(int id){	
		try{
			ServicosBase servicosBase = getBean();
			return servicosBase.buscarServicoPorId(id);
		}catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getCause() + "\n");
			sb.append(e.getMessage() + "\n");
			sb.append(e.getStackTrace());
			
			e.printStackTrace();

			return null;
		}
	}

	public List<Servicos> buscarServicoPorIdEstabelecimento(int idEstabelecimento){	
		try{
			ServicosBase servicosBase = getBean();
			return servicosBase.buscarServicoPorIdEstabelecimento(idEstabelecimento);
		}catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getCause() + "\n");
			sb.append(e.getMessage() + "\n");
			sb.append(e.getStackTrace());
			
			e.printStackTrace();

			return null;
		}
	}
	
    public ServicosBase getBean() throws Exception {
    	
        Properties prop = Utils.getProperties();     
        Context ctx = new InitialContext(prop); 
        Object ref = ctx.lookup(prop.getProperty("SERVICOS_LOOKUP"));       
      
        return (ServicosBase)PortableRemoteObject.narrow(ref, ServicosBase.class);
    }
}
